// 评论和互动服务
// 处理评论、点赞、收藏、弹幕等互动功能

import { dataService } from './simpleDbService.js'

// 模拟API延迟
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms))

// 评论服务
export const commentService = {
  // 添加评论
  async addComment(videoId, content, userId, parentId = null) {
    try {
      await delay(300)
      
      const comment = {
        id: `comment_${Date.now()}`,
        videoId,
        userId,
        content,
        parentId,
        createdAt: new Date().toISOString(),
        likes: 0,
        dislikes: 0,
        replies: 0,
        isLiked: false,
        isDisliked: false
      }
      
      // 保存到数据库
      const newComment = dataService.comments.create(comment)
      
      // 更新视频的评论数
      const video = dataService.videos.getById(videoId)
      if (video) {
        dataService.videos.update(videoId, { comments: (video.comments || 0) + 1 })
      }
      
      return newComment
    } catch (error) {
      console.error('添加评论失败:', error)
      throw error
    }
  },
  
  // 获取视频评论
  async getComments(videoId, page = 1, limit = 20) {
    try {
      await delay(200)
      
      // 从数据库获取评论
      let comments = dataService.comments.getByVideoId(videoId)
      
      // 分页处理
      const start = (page - 1) * limit
      const end = start + limit
      
      return {
        comments: comments.slice(start, end),
        total: comments.length,
        page,
        limit,
        totalPages: Math.ceil(comments.length / limit)
      }
    } catch (error) {
      console.error('获取评论失败:', error)
      throw error
    }
  },
  
  // 删除评论
  async deleteComment(commentId) {
    try {
      await delay(200)
      
      // 从数据库删除评论
      dataService.comments.delete(commentId)
      
      return { success: true, message: '评论删除成功' }
    } catch (error) {
      console.error('删除评论失败:', error)
      throw error
    }
  },
  
  // 点赞评论
  async likeComment(commentId, userId) {
    try {
      await delay(100)
      
      // 获取评论
      const comment = dataService.comments.getById(commentId)
      if (!comment) {
        throw new Error('评论不存在')
      }
      
      // 更新点赞状态
      dataService.comments.update(commentId, {
        likes: comment.likes + 1,
        isLiked: true,
        isDisliked: false
      })
      
      return { success: true, likes: comment.likes + 1 }
    } catch (error) {
      console.error('点赞评论失败:', error)
      throw error
    }
  },
  
  // 取消点赞
  async unlikeComment(commentId, userId) {
    try {
      await delay(100)
      
      // 获取评论
      const comment = dataService.comments.getById(commentId)
      if (!comment) {
        throw new Error('评论不存在')
      }
      
      // 更新点赞状态
      dataService.comments.update(commentId, {
        likes: Math.max(0, comment.likes - 1),
        isLiked: false
      })
      
      return { success: true, likes: Math.max(0, comment.likes - 1) }
    } catch (error) {
      console.error('取消点赞失败:', error)
      throw error
    }
  }
}

// 点赞服务
export const likeService = {
  // 点赞视频
  async likeVideo(videoId, userId) {
    try {
      await delay(100)
      
      // 获取视频
      const video = dataService.videos.getById(videoId)
      if (!video) {
        throw new Error('视频不存在')
      }
      
      // 更新点赞数
      dataService.videos.update(videoId, {
        likes: (video.likes || 0) + 1
      })
      
      // 记录用户点赞
      const user = dataService.users.getById(userId)
      if (user) {
        const likes = [...(user.likes || [])]
        if (!likes.includes(videoId)) {
          likes.push(videoId)
          dataService.users.update(userId, { likes })
        }
      }
      
      return { success: true, likes: (video.likes || 0) + 1 }
    } catch (error) {
      console.error('点赞视频失败:', error)
      throw error
    }
  },
  
  // 取消点赞
  async unlikeVideo(videoId, userId) {
    try {
      await delay(100)
      
      // 获取视频
      const video = dataService.videos.getById(videoId)
      if (!video) {
        throw new Error('视频不存在')
      }
      
      // 更新点赞数
      dataService.videos.update(videoId, {
        likes: Math.max(0, (video.likes || 0) - 1)
      })
      
      // 移除用户点赞记录
      const user = dataService.users.getById(userId)
      if (user) {
        const likes = [...(user.likes || [])]
        const index = likes.indexOf(videoId)
        if (index >= 0) {
          likes.splice(index, 1)
          dataService.users.update(userId, { likes })
        }
      }
      
      return { success: true, likes: Math.max(0, (video.likes || 0) - 1) }
    } catch (error) {
      console.error('取消点赞失败:', error)
      throw error
    }
  },
  
  // 检查是否已点赞
  async isLiked(videoId, userId) {
    try {
      await delay(50)
      
      const user = dataService.users.getById(userId)
      return user && user.likes && user.likes.includes(videoId)
    } catch (error) {
      console.error('检查点赞状态失败:', error)
      return false
    }
  }
}

// 收藏服务
export const favoriteService = {
  // 收藏视频
  async favoriteVideo(videoId, userId, folderId = 'default') {
    try {
      await delay(200)
      
      // 获取用户
      const user = dataService.users.getById(userId)
      if (!user) {
        throw new Error('用户不存在')
      }
      
      // 获取收藏夹
      let favorites = user.favorites || []
      
      // 检查是否已收藏
      const existingIndex = favorites.findIndex(fav => fav.videoId === videoId)
      if (existingIndex >= 0) {
        return { success: false, message: '已收藏该视频' }
      }
      
      // 添加收藏
      favorites.push({
        videoId,
        folderId,
        createdAt: new Date().toISOString()
      })
      
      // 更新用户收藏
      dataService.users.update(userId, { favorites })
      
      return { success: true, message: '收藏成功' }
    } catch (error) {
      console.error('收藏视频失败:', error)
      throw error
    }
  },
  
  // 取消收藏
  async unfavoriteVideo(videoId, userId) {
    try {
      await delay(200)
      
      // 获取用户
      const user = dataService.users.getById(userId)
      if (!user) {
        throw new Error('用户不存在')
      }
      
      // 获取收藏夹
      let favorites = user.favorites || []
      
      // 移除收藏
      favorites = favorites.filter(fav => fav.videoId !== videoId)
      
      // 更新用户收藏
      dataService.users.update(userId, { favorites })
      
      return { success: true, message: '取消收藏成功' }
    } catch (error) {
      console.error('取消收藏失败:', error)
      throw error
    }
  },
  
  // 检查是否已收藏
  async isFavorited(videoId, userId) {
    try {
      await delay(50)
      
      const user = dataService.users.getById(userId)
      return user && user.favorites && user.favorites.some(fav => fav.videoId === videoId)
    } catch (error) {
      console.error('检查收藏状态失败:', error)
      return false
    }
  },
  
  // 获取用户收藏列表
  async getUserFavorites(userId, page = 1, limit = 20) {
    try {
      await delay(300)
      
      const user = dataService.users.getById(userId)
      if (!user || !user.favorites || user.favorites.length === 0) {
        return { videos: [], total: 0, page, limit, totalPages: 0 }
      }
      
      // 获取收藏的视频ID
      const videoIds = user.favorites.map(fav => fav.videoId)
      
      // 从数据库获取视频
      const allVideos = dataService.videos.getAll()
      const favoriteVideos = allVideos.filter(video => videoIds.includes(video.id))
      
      // 分页处理
      const start = (page - 1) * limit
      const end = start + limit
      
      return {
        videos: favoriteVideos.slice(start, end),
        total: favoriteVideos.length,
        page,
        limit,
        totalPages: Math.ceil(favoriteVideos.length / limit)
      }
    } catch (error) {
      console.error('获取收藏列表失败:', error)
      throw error
    }
  }
}

// 弹幕服务
export const danmakuService = {
  // 发送弹幕
  async sendDanmaku(videoId, content, timestamp, userId) {
    try {
      await delay(100)
      
      const danmaku = {
        id: `danmaku_${Date.now()}`,
        videoId,
        userId,
        content,
        timestamp,
        createdAt: new Date().toISOString(),
        color: '#FFFFFF',
        mode: 'scroll' // scroll, top, bottom
      }
      
      // 在实际项目中，这里应该调用API保存弹幕
      // const response = await fetch('/api/danmakus', {
      //   method: 'POST',
      //   headers: { 'Content-Type': 'application/json' },
      //   body: JSON.stringify(danmaku)
      // })
      // return await response.json()
      
      return danmaku
    } catch (error) {
      console.error('发送弹幕失败:', error)
      throw error
    }
  },
  
  // 获取视频弹幕
  async getDanmakus(videoId) {
    try {
      await delay(200)
      
      // 模拟返回弹幕数据
      const danmakus = []
      const maxDanmakus = 50
      const maxTime = 600 // 假设视频最长10分钟
      
      for (let i = 0; i < maxDanmakus; i++) {
        danmakus.push({
          id: `danmaku_${i}`,
          videoId,
          userId: `user_${Math.floor(Math.random() * 100)}`,
          content: this.getRandomDanmakuContent(),
          timestamp: Math.random() * maxTime,
          createdAt: new Date(Date.now() - Math.random() * 86400000).toISOString(),
          color: this.getRandomColor(),
          mode: ['scroll', 'top', 'bottom'][Math.floor(Math.random() * 3)]
        })
      }
      
      return danmakus
    } catch (error) {
      console.error('获取弹幕失败:', error)
      throw error
    }
  },
  
  // 辅助函数：获取随机弹幕内容
  getRandomDanmakuContent() {
    const contents = [
      '前方高能！',
      '666666',
      '哈哈哈',
      '学到了',
      '太精彩了',
      '这个视频真不错',
      '主播加油！',
      '打卡',
      '路过',
      '收藏了'
    ]
    return contents[Math.floor(Math.random() * contents.length)]
  },
  
  // 辅助函数：获取随机颜色
  getRandomColor() {
    const colors = ['#FFFFFF', '#FFFF00', '#FF0000', '#00FF00', '#00FFFF', '#FF00FF']
    return colors[Math.floor(Math.random() * colors.length)]
  }
}

// 导出默认服务
export default {
  commentService,
  likeService,
  favoriteService,
  danmakuService
}